﻿using Castle.DynamicProxy;
using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Admin.Model;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace CNKI.TPI.Web.UI.Controllers.Admin
{
    public class Admin_TopicController : BaseController
    {
        private ISubjectHomeService subjectService = null;
        private ISingleDBPublishService singleService = null;
        private ISearchService searchService = null;
        public Admin_TopicController(ISubjectHomeService subjectService, ISingleDBPublishService singleService, ISearchService searchService)
        {
            this.subjectService = generator.CreateInterfaceProxyWithTarget<ISubjectHomeService>(subjectService, new IInterceptor[] { new LogInterceptor() });
            this.singleService = generator.CreateInterfaceProxyWithTarget<ISingleDBPublishService>(singleService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
        }
        //
        // GET: /Admin_Topic/

        public ActionResult Index()
        {
            return View();
        }

        //public ActionResult ClsNodeQueryEdit()
        //{
        //    return View();
        //}
        public ActionResult CategoryNavManager()
        {
            return View();
        }
        public ActionResult SubjectHomePage()
        {
            return View();
        }
        public ActionResult DBManager()
        {
            return View();
        }
        public ActionResult CategoryDataList(string name, string code, string navName, string navCode)
        {
            ViewBag.CLSName = name;  
            ViewBag.CLSSysCode = code;
            ViewBag.NavCode = navCode;
            ViewBag.NavName = navName;//导航
            return View();
        }
        public ActionResult ClsNodeQueryEdit(string name, string code, string navcode,string navname)
        {
            ViewBag.NodeName = name;  //nodename
            ViewBag.NodeSysCode = code;
            ViewBag.NavCode = navcode;
            ViewBag.NavName = navname;//导航
            ViewBag.DatabaseList = singleService.GetDBList(null).Where(c => c.VisibleFlag == 1 && c.DatabasePubFlag == 1).ToList();
            return View();
        }
        public ActionResult CategorySet(string name, string code)
        {
            ViewBag.NavName = name;
            ViewBag.NavCode = code;
            ViewBag.CateList = subjectService.GetCateByNavCode(code).OrderBy(c => c.SySCode).ToList();
            return View();
        }
        public ActionResult DBSet(string sysid, string name, string status)
        {
            ViewBag.SYSID = sysid;
            ViewBag.Name = name;
            ViewBag.Status = status;

            return PartialView("DBSet");
        }
        public ActionResult SubjectSetList(string TopicName, string TopicCode, string TopicDB)
        {
            ViewBag.TopicName = TopicName;
            ViewBag.TopicCode = TopicCode;
            ViewBag.TopicDB = TopicDB;

            return View();
        }
        public JsonResult DBList(string sysid)
        {
            SYS_CMS_TOPIC_DBCONFIG DBList = subjectService.GetDBBySysId(sysid)[0];
            IList<SYS_CMS_TOPIC_DBCONFIG> result = new List<SYS_CMS_TOPIC_DBCONFIG>();

            string[] dbcode = DBList.DBCode.Split(',');
            string[] dbname = DBList.DBName.Split(',');
            string[] dbid   = DBList.DBID.Split(',');
            for (int i=0; i<dbcode.Length; i++)
            {
                result.Add(new SYS_CMS_TOPIC_DBCONFIG()
                {
                    DBCode=dbcode[i],
                    DBName=dbname[i],
                    DBID= dbid[i]
                });
            }

            var res = new JsonResult();
            res.Data = result;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
        /// <summary>
        /// 专题栏目查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult PageConfigSearch(string columnname, string topiccode, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_TOPIC_PAGECONFIG> list = subjectService.GetPageConfigPageSize(columnname, topiccode, (pageIndexNow - 1) * pageSize, pageSize, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.PageConfigList = list;
            }
            ViewBag.PageAll = subjectService.GetPageConfigAll().OrderBy(c => c.SORTNO).ToList();
            pageList(pageIndexNow, pageSize, count);
            ViewBag.TopicCode = topiccode;
            return PartialView("SubjectSetResult");

        }
        public ActionResult SubjectSetInfo(string TopicCode, string TopicName, string TopicDB, string SysID, string DBCode)
        {
            ViewBag.TopicCode = TopicCode;
            ViewBag.TopicName = TopicName;
            ViewBag.TopicDB = TopicDB;
            ViewBag.DBCode = DBCode;
            ViewBag.SysID = SysID;
            IList<SYS_CMS_TOPIC_CLS> listcls = subjectService.GetNavAll();
            ViewBag.ClsList = listcls;

            SYS_CMS_TOPIC_DBCONFIG DBList = subjectService.GetDBBySysId(TopicDB)[0];
            IList<SYS_CMS_TOPIC_DBCONFIG> result = new List<SYS_CMS_TOPIC_DBCONFIG>();

            string[] dbcode = DBList.DBCode.Split(',');
            string[] dbname = DBList.DBName.Split(',');
            for (int i = 0; i < dbcode.Length; i++)
            {
                result.Add(new SYS_CMS_TOPIC_DBCONFIG()
                {
                    DBCode = dbcode[i],
                    DBName = dbname[i]
                });
            }
            ViewBag.DBList = result;

            if (SysID != "0") //编辑
            {
                IList<SYS_CMS_TOPIC_PAGECONFIG> list = subjectService.GetPageConfigByID(SysID);
                if (list != null && list.Count > 0)
                {
                    ViewBag.PageInfo = list[0];
                    IList<SYS_CMS_TOPIC_CLS_NODE> nodelist = subjectService.GetByCLSNodeCode(list[0].CLSCode, list[0].NodeCode);

                    string clsname = listcls.Where(c => c.CLSCode == list[0].CLSCode).ToList()[0].CLSName;
                    ViewBag.CLsNode = listcls.Where(c => c.CLSCode == list[0].CLSCode).ToList()[0].CLSCode;
                    if (nodelist != null && nodelist.Count > 0)
                    {
                        ViewBag.CLsNodeName = clsname + "--" + nodelist[0].NodeName;
                        
                    }
                }

            }

            return View("SubjectSetInfo");
        }
        /// <summary>
        /// 专题库查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult SubjectHomeSearch(string subjectname, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_TOPIC> list = subjectService.GetTopicByNamePageSize(subjectname, (pageIndexNow - 1) * pageSize, pageSize, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.SubjectList = list;
            }

            IList<SYS_CMS_TOPIC_DBCONFIG> dblist = subjectService.GetDBAll();
            if (dblist != null && dblist.Count > 0)
            {
                ViewBag.DBList = dblist;
            }

            pageList(pageIndexNow, pageSize, count);
            return PartialView("SubjectHomeResult");

        }
        /// <summary>
        /// 分类查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult CategoryNavSearch(string navname, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_TOPIC_CLS> list = subjectService.GetNavByNamePageSize(navname, (pageIndexNow - 1) * pageSize, pageSize, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.NavList = list;
            }
            pageList(pageIndexNow, pageSize, count);
            return PartialView("CategoryNavResult");

        }
        /// <summary>
        /// 分类查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult DBSearch(string dbname, int pageIndexNow)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_TOPIC_DBCONFIG> list = subjectService.GetDBByNamePageSize(dbname, (pageIndexNow - 1) * pageSize, pageSize, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.DBList = list;
            }
            pageList(pageIndexNow, pageSize, count);
            return PartialView("DBResult");

        }
        /// <summary>
        /// 分类条件查询
        /// </summary>
        /// <returns></returns>
        [ValidateInput(false)]
        public ActionResult CategoryQuerySearch(string dbname, string nodecode, int pageIndexNow, string navCode)
        {
            int pageSize = 10;//每页显示记录数
            int count = 0;//总条数
            IList<SYS_CMS_TOPIC_CLS_QUERY> list = subjectService.GetQueryPageSize(dbname, nodecode,navCode,(pageIndexNow - 1) * pageSize, pageSize, out count);
            if (list != null && list.Count > 0)
            {
                ViewBag.QueryList = list;
            }
            pageList(pageIndexNow, pageSize, count);
            return PartialView("CategoryQueryResult");

        }
        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="list"></param>
        /// <param name="pageIndexNow"></param>
        /// <param name="pageSize"></param>
        /// <param name="count"></param>
        private void pageList(int pageIndexNow, int pageSize, int count)
        {
            int sumPage = 0;//一共多少页
            int disPgae = 8;  //默认显示页数，当页数大于该数值时，按规定格式显示
            sumPage = count / pageSize; //一共多少页
            if (count % pageSize != 0)
            {
                sumPage = sumPage + 1;
            }
            ColumnAliasHelper com = new ColumnAliasHelper();
            ViewBag.TotalPage = sumPage;
            ViewBag.PageList = com.GetPageList(pageIndexNow, sumPage, disPgae);
            ViewBag.PageNow = pageIndexNow;//当前页
            ViewBag.PageSize = pageSize;
            ViewBag.Count = count;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveSubject()
        {
            SYS_CMS_TOPIC obj = new SYS_CMS_TOPIC();
            obj.TopicName = Request["subjectname"];
            obj.TopicCode = Request["code"];
            obj.TopicStatus = int.Parse(Request["status"]);
            obj.TopicDB = int.Parse(Request["topicdb"]);
            obj.CopyRight = Request["copyright"];
            obj.SYSID = int.Parse(Request["sysid"]);
            obj.TopicPage = Request["subjectpage"];
            obj.Domain = Request["domain"];
            if (Request.Files.Count > 0)
            {
                string fileName = "";
                string rootPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "TopicLogo";
                if (!System.IO.Directory.Exists(rootPath))
                {
                    //创建文件夹
                    File_Oper.CreateDirectory(rootPath);
                    //去掉文件夹的只读属性
                    System.IO.DirectoryInfo DirInfo = new DirectoryInfo(rootPath);
                    DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
                }
                string extraName = Request.Files[0].FileName.Substring(Request.Files[0].FileName.LastIndexOf(".") + 1); //后缀;
                fileName = Guid.NewGuid().ToString()+ "." + extraName;
                Request.Files[0].SaveAs(rootPath + Path.DirectorySeparatorChar + fileName);
                obj.TopicPic = "../TopicLogo/" + fileName;
            }

            IISHelper.CreateSite(obj.Domain);
            return subjectService.SaveTopic(obj);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DelSubject(string sysidstr)
        {
            return subjectService.DeleteSubject(sysidstr);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveNav(SYS_CMS_TOPIC_CLS obj)
        {
            return subjectService.SaveNav(obj);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DelNav(string sysidstr)
        {
            return subjectService.DeleteNav(sysidstr);
        }
        public bool DelDB(string sysidstr)
        {
            return subjectService.DeleteDB(sysidstr);
        }
        public bool IsExitNav(string name, int sysid)
        {
            return subjectService.IsExistNav(name, sysid);
        }
        public bool IsExitDB(string name, int sysid)
        {
            return subjectService.IsExistDB(name, sysid);
        }
        public bool IsExitSubject(string name, int sysid)
        {
            return subjectService.IsExistSubject(name, sysid);
        }


        public bool SaveDB(SYS_CMS_TOPIC_DBCONFIG obj)
        {
            return subjectService.SaveDB(obj);
        }

        public bool SaveDBList(SYS_CMS_TOPIC_DBCONFIG obj)
        {
            return subjectService.SaveDB(obj);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool SaveNavCate(string clscode, int sysid, string nodename, string parentcode, int grade)
        {
            grade = grade + 1;
            return subjectService.SaveNavCate(clscode, sysid, nodename, parentcode, grade);
        }

        public JsonResult GetCateCodeChilds(string codestr, string clscode)
        {
            string[] array = codestr.Split(',');
            string code = array[0];
            int grade = int.Parse(array[1]) + 1;

            IList<SYS_CMS_TOPIC_CLS_NODE> DeptList = subjectService.GetCateChilds(clscode, grade, code);
            var res = new JsonResult();
            res.Data = DeptList;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DelNavCLs(string syscodestr, string clsCode)
        {
            return subjectService.DeleteCLsNode(syscodestr, clsCode);
        }
        /// <summary>
        /// 获取检索字段
        /// </summary>
        /// <param name="dbID"></param>
        /// <returns></returns>
        public JsonResult GetDBSearchField(int dbID)
        {

            //检索字段
            SYS_CMS_DATABASE dbinfo = searchService.GetDataByID(dbID);
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> searchField = searchService.GetSearchFieldList(dbID);
            if ((searchField == null || searchField.Count == 0) && dbinfo.DatabaseType == 11)
            {
                searchField = new List<SYS_CMS_DATABASE_PUBLISH_FIELD>();
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "标题", FieldDispName = "标题" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "作者", FieldDispName = "作者" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "发布单位", FieldDispName = "发布单位" });
                searchField.Add(new SYS_CMS_DATABASE_PUBLISH_FIELD { FieldName = "全文", FieldDispName = "全文" });
            }
            var res = new JsonResult();
            res.Data = searchField;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
        /// <summary>
        /// 保存查询条件
        /// </summary>
        /// <returns></returns>
        public bool SaveQuery()
        {

            IList<SearchQuery> searchQuery = new List<SearchQuery>();
            string checkedCatID = Request["beforecheckedCatID"];
            int currentSubid = int.Parse(Request["currentSubid"]);
            int selectedCatTypeID = 0;
            if (Request["beforeselectedCatTypeID"] != null && Request["beforeselectedCatTypeID"] != "")
            {
                selectedCatTypeID = int.Parse(Request["beforeselectedCatTypeID"]);
            }
            int dbID = int.Parse(Request["dbID"]);
            string dbName = Request["dbName"];

            string conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue"]) ? "" : Request["beforeConditionValue"];
            int Querystr = string.IsNullOrEmpty(Request["beforeQueryValue"]) ? 0 : int.Parse(Request["beforeQueryValue"].ToString());
            searchQuery.Add(new SearchQuery(Request["beforeConditionKey"], conditionValue, (ConditionType)Querystr));
            string contype = "";
            string conkey = "";
            for (int i = 1; i <= currentSubid; i++)
            {
                Querystr = string.IsNullOrEmpty(Request["beforeQueryValue" + i]) ? 0 : int.Parse(Request["beforeQueryValue" + i].ToString());//模糊精确
                conditionValue = string.IsNullOrEmpty(Request["beforeConditionValue" + i]) ? "" : Request["beforeConditionValue" + i];//值
                contype = string.IsNullOrEmpty(Request["beforeConditionType" + i]) ? "0" : Request["beforeConditionType" + i];//and or
                conkey = string.IsNullOrEmpty(Request["beforeConditionKey" + i]) ? "" : Request["beforeConditionKey" + i];//关键词
                searchQuery.Add(new SearchQuery(conkey, conditionValue, (ConditionType)Querystr, (SearchMatchType)int.Parse(contype)));
            }
            string strOrder = "";
            string sortstr = "desc";
            IList<SYS_CMS_DATABASE_PUBLISH_FIELD> listSort = searchService.GetSortFieldList(dbID);//排序字段集合
            SYS_CMS_DATABASE obj = searchService.GetDataByID(dbID);
            if (listSort != null && listSort.Count > 0) //初始化
            {
                strOrder = listSort[0].FieldName;//默认排序字段
            }
            if (!String.IsNullOrEmpty(Request["sortField"]))
            {
                strOrder = Request["sortField"].ToString();
            }
            if (!String.IsNullOrEmpty(Request["sortDescAsc"]))
            {
                sortstr = Request["sortDescAsc"].ToString();
            }
            string dbDisplayName = Request["DBDisplayName"].ToString();
            string nodeCode = Request["nodecode"].ToString();
            string clsCode = Request["NavCode"].ToString();
            return subjectService.SaveQuery(strOrder + " " + sortstr, searchQuery, dbName, dbDisplayName, nodeCode, clsCode);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sysidstr"></param>
        /// <returns></returns>
        public bool DelCLSQuery(string sysidstr)
        {
            return subjectService.DeleteCLsQuery(sysidstr);
        }

        public string GetClsTreeInfo(string clsCode)
        {
            StringBuilder treeContent = new StringBuilder();
            IList<SYS_CMS_TOPIC_CLS_NODE> categoryList = subjectService.GetCateByNavCode(clsCode).OrderBy(c => c.SySCode).ToList();
            if (categoryList != null && categoryList.Count > 0)
            {
                treeContent.Append("<tree id=\"0\">");
                int preFlag = 0;
                foreach (SYS_CMS_TOPIC_CLS_NODE obj in categoryList)
                {
                    if (obj.Grade < preFlag)
                    {
                        for (var j = 0; j < preFlag - obj.Grade; j++)
                        {
                            treeContent.Append("</item>");
                        }
                    }
                    preFlag = obj.Grade;
                    treeContent.Append("<item  id=\"" + obj.SySCode + "\" text=\"" + obj.NodeName + "\">");
                    if (1 != obj.ChildFlag)
                    {
                        treeContent.Append("</item>");
                    }
                }
                for (var i = 0; i < preFlag - 1; i++)
                {
                    treeContent.Append("</item>");
                }
                treeContent.Append("</tree>");
            }

            return treeContent.ToString();

        }

        public JsonResult GetDBCls(string nodecode,string clscode)
        {
            var res = new JsonResult();
            IList<SYS_CMS_TOPIC_CLS_QUERY> list = subjectService.GetQueryByNodeCode(nodecode,clscode);
            if (list != null && list.Count > 0)
            {
                res.Data = list;
            }
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。  
            return res;
        }

        public bool SavePageConfig(SYS_CMS_TOPIC_PAGECONFIG obj)
        {
            return subjectService.SavePageConfig(obj);
        }
        public bool DeletePageConfig(string sysidstr)
        {
            return subjectService.DeletePageConfig(sysidstr);
        }
        public bool UpdatePageSort(IList<SYS_CMS_TOPIC_PAGECONFIG> list)
        {
            return subjectService.UpdatePageSort(list);
        }
        public JsonResult GetPageConfig(string topiccode)
        {
            IList<SYS_CMS_TOPIC_PAGECONFIG> list = subjectService.GetPageConfigAll().Where(c=>c.TopicCode==topiccode).OrderBy(c => c.SORTNO).ToList();
            //获取字段
            var res = new JsonResult();
            res.Data = list;
            res.MaxJsonLength = 102400000;
            res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;//允许使用GET方式获取，否则用GET获取是会报错。 
            return res;

        }
    }
}
